<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.ResourceBundle" %>
<%@ page import="java.util.UUID" %>
<%@ page import="java.util.Collections" %>
<%@ page import="java.util.Comparator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.ErpCoreModel.Base.*" %>
<%@ page import="com.ErpCoreModel.Framework.*" %>
<%@ page import="com.ErpCoreModel.UI.*" %>

<%@ page import="com.ErpCoreWeb.Common.Global" %>

<%!CCompany m_Company = null;
String m_sBackImg = "../images/default.jpg";
CDesktopAppMgr m_DesktopAppMgr= null;
CUserMenuMgr m_UserMenuMgr=null;
CDesktopGroupMgr m_DesktopGroupMgr = null;
UUID m_guidCurGroupId = Util.GetEmptyUUID();
CDesktopGroup m_CurGroup = null;

//排序菜单
public List<CBaseObject> GetOrderMenu(HttpServletRequest request)
{
    List<CBaseObject> lstRet = new ArrayList<CBaseObject>();

    //用户菜单
    List<CBaseObject> lstObj = m_UserMenuMgr.GetList();
    for (int i = 0; i < lstObj.size(); i++)
    {
        CUserMenu UserMenu = (CUserMenu)lstObj.get(i);
        if (!UserMenu.getUI_DesktopGroup_id().equals(m_guidCurGroupId))
            continue;

        lstRet.add(UserMenu);
    }
    //角色菜单
    List<CBaseObject> lstObjR = m_Company.getRoleMgr().GetList();
    for (int i=0;i< lstObjR.size();i++)
    {
        CRole Role = (CRole)lstObjR.get(i);
        if (!((CUser)request.getSession().getAttribute("User")).IsRole(Role.getName()))
            continue;
        List<CBaseObject> lstObjRM = Role.getRoleMenuMgr().GetList();
        for (int j=0;j< lstObjRM.size();j++)
        {
            CRoleMenu RoleMenu = (CRoleMenu)lstObjRM.get(j);
            if (!RoleMenu.getUI_DesktopGroup_id().equals(m_guidCurGroupId))
                continue;

            lstRet.add(RoleMenu);
        }
    }
    //桌面应用
    lstObj = m_DesktopAppMgr.GetList();
    for (int i = 0; i < lstObj.size(); i++)
    {
        CDesktopApp App = (CDesktopApp)lstObj.get(i);
        if (!App.getUI_DesktopGroup_id().equals(m_guidCurGroupId))
            continue;

        lstRet.add(App);
    }

    ComparatorIdx comparator=new ComparatorIdx();
    Collections.sort(lstRet, comparator);

    return lstRet;
}
class ComparatorIdx implements Comparator{

	 public int compare(Object arg0, Object arg1) {
	   CBaseObject obj0=(CBaseObject)arg0;
	   CBaseObject obj1=(CBaseObject)arg1;

	   return GetIdx(obj0)-GetIdx(obj1);
	  }
	 int GetIdx(CBaseObject obj)
	 {
		 if(obj.m_arrNewVal.containsKey("idx"))
			 return obj.m_arrNewVal.get("idx").IntVal;
		 return 0;
	 }
}%>
<%
	m_DesktopGroupMgr = Global.GetCtx(request.getSession().getAttribute("TopCompany").toString(),this.getServletContext()).getDesktopGroupMgr();

String GroupId = request.getParameter("GroupId");
if (GroupId!=null && GroupId.length()>0)
{
    m_guidCurGroupId = UUID.fromString(GroupId);
    m_CurGroup = (CDesktopGroup)m_DesktopGroupMgr.Find(m_guidCurGroupId);
}

//桌面背景
m_sBackImg = String.format("../%s/DesktopImg/default.jpg", Global.GetDesktopIconPathName());
CUser user = (CUser)request.getSession().getAttribute("User");
if(user!=null)
{
	m_Company = (CCompany)Global.GetCtx(request.getSession().getAttribute("TopCompany").toString(),this.getServletContext()).getCompanyMgr().Find(user.getB_Company_id());
	
	CDesktop desktop = (CDesktop)user.getDesktopMgr().GetFirstObj();
	if (desktop != null && desktop.getBackImg().length()>0)
	    m_sBackImg = String.format("../%s/DesktopImg/%s", Global.GetDesktopIconPathName(), desktop.getBackImg()); 
	
	m_UserMenuMgr = user.getUserMenuMgr();
	m_DesktopAppMgr = user.getDesktopAppMgr();
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title><%=com.ErpCoreWeb.Common.Util.getConfigValue("ProductName")%></title>
    <link href="../lib/ligerUI/skins/Aqua/css/ligerui-all.css" rel="stylesheet" type="text/css" /> 
    <script src="../lib/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="../lib/ligerUI/js/core/base.js" type="text/javascript"></script>
    <script src="../lib/ligerUI/js/plugins/ligerDrag.js" type="text/javascript"></script>
    <script src="../lib/ligerUI/js/plugins/ligerDialog.js" type="text/javascript"></script>
    <script src="../lib/ligerUI/js/plugins/ligerResizable.js" type="text/javascript"></script>
    <script src="../lib/ligerUI/js/plugins/ligerMenu.js" type="text/javascript"></script>
    <script src="../js/Hashtable.js" type="text/javascript"></script>

    <script type="text/javascript">
        function btModPwd_onclick() {
            var winModPwd = $.ligerDialog.open(
            { url: '../ModPwd.jsp', height: 300, width: 450, isResize: true, modal: false, title: '登录', slide: false
                //        , buttons: [
                //            { text: '确定', onclick: function (item, Dialog, index) {
                //                win.hide();
                //            }
                //            }
                //        ]
            });
        }
    </script>
    <style  type="text/css">
    <!--
    .trans_msg
        {
        filter:alpha(opacity=100,enabled=1) revealTrans(duration=.2,transition=1) blendtrans(duration=.2);
        }
    -->
    </style>
    <style type="text/css">
        .l-case-title
        {
            font-weight: bold;
            margin-top: 20px;
            margin-bottom: 20px;
        }
        body, html
        {
            width: 100%;
            height: 100%;
        }
        *
        {
            margin: 0;
            padding: 0;
        }
        #winlinks
        {
            position: absolute;
            left: 50px;
            top: 20px;
            width: 100%;
        }
        #winlinks ul
        {
            position: relative;
        }
        #winlinks li
        {
            width: 70px;
            cursor: pointer;
            height: 80px;
            position: absolute;
            z-index: 101;
            list-style: none;
            text-align: center;
        }
        #winlinks li img
        {
            width: 64px;
            height: 64px;
        }
        #winlinks li span
        {
            background: none repeat scroll 0 0 rgba(0, 0, 0, 0.3);
            border-radius: 10px 10px 10px 10px;
            display: block;
            font-size: 12px;
            margin-top: 1px;
            color: White;
            line-height: 18px;
            text-align: center;
        }
        #winlinks li.l-over div.bg
        {
            display: block;
        }
        #winlinks li div.bg
        {
            display: none;
            position: absolute;
            top: -2px;
            left: -2px;
            z-index: 0;
            width: 75px;
            height: 64px;
            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            border-radius: 5px;
            background: #000;
            opacity: 0.1;
            filter: alpha(opacity=10);
        }
        #grouptitle li span
        {
            background: none repeat scroll 0 0 rgba(0, 0, 0, 0.3);
            border-radius: 10px 10px 10px 10px;
            display: block;
            font-size: 12px;
            margin-top: 1px;
            color: White;
            line-height: 18px;
            text-align: center;
        }
        .l-taskbar-task-icon
        {
            top: 3px; left: 6px; background-image:none;
        } 
        .l-taskbar-task-content{ margin-left:30px;}
        .l-taskbar-task-icon img
        {
            width: 22px;
            height: 22px;
        }
        .close
        {
            position:absolute;
            left:50px;
        } 
    </style>
</head>
<body style="overflow: hidden; background: url(<%=m_sBackImg %>) no-repeat  center center;">
    <%
      if (request.getSession().getAttribute("User") != null)
      {%>
    <div style="float: right; margin-right: 30px; margin-top: 15px;">
        <input id="btModPwd" type="button" style="width:100px" value="修改密码"   onclick="return btModPwd_onclick()"/></div>
    <%} %>
    <div id="winlinks">
        <ul>
        </ul>
    </div>
    <div style="position:absolute;bottom:75px;  width:100%;  text-align:center;">
    <div id="grouptitle" style=" text-align:center; width:150px;  margin:0 auto;">
    <ul><li><span id="spanTitle" ><%=(m_CurGroup!=null)?m_CurGroup.getName():"主桌面" %></span></li></ul>
    </div>
    <script type="text/javascript">
        var CurGroup = '<%=(m_CurGroup!=null)?m_CurGroup.getName():"主桌面" %>';
    </script>
    </div>
    <div style="position:absolute;bottom:50px;  width:100%;  text-align:center;">
    <div style=" text-align:center;">
    <input type="radio" id="rdDefault" name="rdDesktopGroup" style=" width:20px; height:20px;" <%if(m_guidCurGroupId.equals(Util.GetEmptyUUID())){ %>checked<%} %> onclick="onClickDesktopGroup('<%=Util.GetEmptyUUID().toString() %>')" 
     onMouseOver="$('#spanTitle').text('主桌面');" onMouseOut="$('#spanTitle').text(CurGroup);"/>&nbsp;
    <%
    if (request.getSession().getAttribute("User") != null)
    {
        List<CBaseObject> lstObjGp = m_DesktopGroupMgr.GetList();
        for (int i=0;i< lstObjGp.size();i++)
        {
            CDesktopGroup group = (CDesktopGroup)lstObjGp.get(i);
      %>
    <input type="radio"  id="rd_<%=group.getId() %>" name="rdDesktopGroup" style=" width:20px; height:20px;" <%if(m_guidCurGroupId.equals(group.getId())){ %>checked<%} %> onclick="onClickDesktopGroup('<%=group.getId() %>')" 
     onMouseOver="$('#spanTitle').text('<%=group.getName() %>');" onMouseOut="$('#spanTitle').text(CurGroup);"/>&nbsp;
    <%}
    } %>
    </div>
    </div>
</body>
<script type="text/javascript">
    function onClickDesktopGroup(groupId) {
        window.location = "Desktop.jsp?GroupId=" + groupId;
    } 
</script>
<script type="text/javascript">
    var LINKWIDTH = 120, LINKHEIGHT = 120, TASKBARHEIGHT = 43;
    var winlinksul =  $("#winlinks ul");
    var win ;
    //var hashWin = new Hashtable(); //窗体哈希表
    function f_open(url, title, icon,mtype,width,height) {
        //如果窗体已经打开，则直接显示
//        if (hashWin.contains(url)) {
//            hashWin._hash[url].show();
//            return;
//        }
        ///////////
        //width==0 默认窗体大小, ==-1 最大化, ==-2新开窗口
        var w=width;
        var h=height;
        if(w<=0) w=1000;
        if(h<=0) h=500;
        
        if(width==-2){
            window.open(url);
            return null;
        }
        
        if(mtype=='AddDesktopApp')
        {
            win= $.ligerDialog.open(
            { name: 'winAddDesktopApp', url: url, height: h,width: w, showMax: true, showToggle: true,  isResize: true, modal: false, title: title, slide: false
                , buttons: [
                    { text: '确定', onclick: function (item, Dialog, index) {
                        var ret = document.getElementById('winAddDesktopApp').contentWindow.onSubmit();
                    }},
                    { text: '取消', onclick: function (item, Dialog, index) {
                        //Dialog.hide();
                        Dialog.close();
                    }}
                ]
            });
        }
        else
        {
            var bShowMin=true;
            if(mtype=='0')
                bShowMin=false;
            win= $.ligerDialog.open(
            {  url: url, height: h,width: w, showMax: true, showToggle: true, showMin: bShowMin, isResize: true, modal: false, title: title, slide: false
            });
            
            if(mtype=='AdminForm'){
                win.max();
            }
            if(width==-1){
                win.max();
            }
        }
        var task = jQuery.ligerui.win.tasks[win.id];
        if (task) {
            $(".l-taskbar-task-icon:first", task).html('<img src="' + icon + '" />');
        }
        //记录窗体到哈希表
        //hashWin.add(url,win);
        
        return win;
    }
    <%if(request.getSession().getAttribute("User")==null)
    { %>
    var links = [];
    <%}
    else
    { %>
    var links = [
        <%
        if(m_guidCurGroupId.equals(Util.GetEmptyUUID()))//主桌面
        {
            if(((CUser)request.getSession().getAttribute("User")).IsRole("管理员"))
            { %>
            { icon: '../<%=Global.GetDesktopIconPathName() %>/MenuIcon/admin.png', title: '系统管理', url: '../AdminForm.jsp',mtype:'AdminForm',winw:'800',winh:'500'},
            <% 
            }%>
        
           { icon: '../<%=Global.GetDesktopIconPathName() %>/MenuIcon/IM.png', title: '我的好友', url: '../IM/Friend.jsp',mtype:'IM',winw:'250',winh:'500' },
        <%
        }
        
        List<CBaseObject> lstMenu = GetOrderMenu(request);
        for( int i=0;i< lstMenu.size();i++)
        {
        	CBaseObject obj=lstMenu.get(i);
            if(obj instanceof CUserMenu)
            {
                 CUserMenu UserMenu = (CUserMenu)obj;
               if(!UserMenu.getUI_DesktopGroup_id().equals( m_guidCurGroupId))
                   continue;
               CMenu menu = (CMenu)Global.GetCtx(request.getSession().getAttribute("TopCompany").toString(),this.getServletContext()).getMenuMgr().Find(UserMenu.getUI_Menu_id());
               if (menu == null)
                   continue;
                
               String sIconUrl = "default.png";
               if (menu.getIconUrl().length()>0)
                   sIconUrl = menu.getIconUrl();
               String url=menu.getUrl();
               if(menu.getMType()==enumMenuType.CatalogMenu)
                   url="SelectMenu.jsp?pid="+menu.getId().toString();
               else if(menu.getMType()==enumMenuType.ViewMenu)
               {
                   CView view = (CView)Global.GetCtx(request.getSession().getAttribute("TopCompany").toString(),this.getServletContext()).getViewMgr().Find(menu.getUI_View_id());
                   if (view == null)
                       continue;
                   if(view.getVType()==enumViewType.Single)
                       url="../View/SingleView.jsp?vid="+view.getId().toString();
                   else if(view.getVType()==enumViewType.MasterDetail)
                       url="../View/MasterDetailView.jsp?vid="+view.getId().toString();
                   else 
                       url="../View/MultMasterDetailView.jsp?vid="+view.getId().toString();
               }
               else if(menu.getMType()== enumMenuType.WindowMenu)
               {
               }
               else if(menu.getMType()== enumMenuType.ReportMenu)
               {
                    url="../Report/RunReport.jsp?id="+menu.getRPT_Report_id().toString();
               }
               String sItem = String.format("{ icon: '../%s/MenuIcon/%s', title: '%s', url: '%s',mtype:'%d',winw:'%d',winh:'%d' },",
                    Global.GetDesktopIconPathName(), sIconUrl, menu.getName(), url,menu.getMType().ordinal(),menu.getOpenwinWidth(),menu.getOpenwinHeight());
               //response.getWriter().print(sItem);
               %><%=sItem%><%
            }
            else if(obj instanceof CRoleMenu)
            {
                 CRoleMenu RoleMenu = (CRoleMenu)obj;
                if (!RoleMenu.getUI_DesktopGroup_id().equals(m_guidCurGroupId))
                    continue;
                CMenu menu = (CMenu)Global.GetCtx(request.getSession().getAttribute("TopCompany").toString(),this.getServletContext()).getMenuMgr().Find(RoleMenu.getUI_Menu_id());
                if (menu == null)
                    continue;
                
               String sIconUrl = "default.png";
               if (menu.getIconUrl().length()>0)
                   sIconUrl = menu.getIconUrl();
               String url=menu.getUrl();
               if(menu.getMType()==enumMenuType.CatalogMenu)
                   url="SelectMenu.jsp?pid="+menu.getId().toString();
               else if(menu.getMType()==enumMenuType.ViewMenu)
               {
                   CView view = (CView)Global.GetCtx(request.getSession().getAttribute("TopCompany").toString(),this.getServletContext()).getViewMgr().Find(menu.getUI_View_id());
                   if (view == null)
                       continue;
                   if(view.getVType()==enumViewType.Single)
                       url="../View/SingleView.jsp?vid="+view.getId().toString();
                   else if(view.getVType()==enumViewType.MasterDetail)
                       url="../View/MasterDetailView.jsp?vid="+view.getId().toString();
                   else 
                       url="../View/MultMasterDetailView.jsp?vid="+view.getId().toString();
               }
               else if(menu.getMType()== enumMenuType.WindowMenu)
               {
               }
               else if(menu.getMType()== enumMenuType.ReportMenu)
               {
                    url="../Report/RunReport.jsp?id="+menu.getRPT_Report_id().toString();
               }
               String sItem = String.format("{ icon: '../%s/MenuIcon/%s', title: '%s', url: '%s',mtype:'%d',winw:'%d',winh:'%d' },",
                    Global.GetDesktopIconPathName(), sIconUrl, menu.getName(), url,menu.getMType().ordinal(),menu.getOpenwinWidth(),menu.getOpenwinHeight());
               //response.getWriter().print(sItem);
               %><%=sItem%><%
            }
            else if(obj instanceof CDesktopApp)
            {
               CDesktopApp App = (CDesktopApp)obj;
               
               String sIconUrl = "default.png";
               if (App.getIconUrl().length()>0)
                   sIconUrl = App.getIconUrl();
               String sItem = String.format("{id:'%s', icon: '../%s/MenuIcon/%s', title: '%s', url: '%s',mtype:'DesktopApp',winw:'%d',winh:'%d' },",
                    App.getId().toString(),Global.GetDesktopIconPathName(), sIconUrl, App.getName(), App.getUrl(),App.getOpenwinWidth(),App.getOpenwinHeight());
               // response.getWriter().print(sItem);
               %><%=sItem%><%
            }
        }
        %>
        { icon: '../<%=Global.GetDesktopIconPathName() %>/MenuIcon/order.png', title: '菜单排序', url: 'OrderMenu.jsp?GroupId=<%=(request.getParameter("GroupId")!=null?request.getParameter("GroupId"):"") %>',mtype:'Order',winw:'600',winh:'400' },
        { icon: '../<%=Global.GetDesktopIconPathName() %>/MenuIcon/add.png', title: '添加应用', url: 'AddDesktopApp.jsp?GroupId=<%=(request.getParameter("GroupId")!=null?request.getParameter("GroupId"):"") %>',mtype:'AddDesktopApp',winw:'350',winh:'300' }
        ];
    <%} %>
         
    function onResize() {
        var linksHeight = $(window).height() - TASKBARHEIGHT;
        var winlinks = $("#winlinks");
        winlinks.height(linksHeight);
        var colMaxNumber = parseInt(linksHeight / LINKHEIGHT);//一列最多显示几个快捷方式
        for (var i = 0, l = links.length; i < l; i++) {
            var link = links[i];
            var jlink = $("li[linkindex=" + i + "]", winlinks);
            var top = (i % colMaxNumber) * LINKHEIGHT, left = parseInt(i / colMaxNumber) * LINKWIDTH;
            if (isNaN(top) || isNaN(left)) continue;
            jlink.css({ top: top, left: left });
        }

    }
    function linksInit() {
        for (var i = 0, l = links.length; i < l; i++) {
            var link = links[i];
            var jlink;
            jlink = $("<li></li>");
            jlink.attr("linkindex", i);
            jlink.append("<img src='" + link.icon + "' />");
            jlink.append("<span>" + link.title + "</span>");
            jlink.append("<div id='linkbg"+i+"' class='bg'></div>");
            jlink.append("<img id='close"+i+"' style='display:none;width:16px;height:16px;' src='close.png' onclick='return onCloseApp("+i+")'/>");
            jlink.hover(function () {
                $(this).addClass("l-over");
                var linkindex = $(this).attr("linkindex");
                var link = links[linkindex];
                if(link.mtype=='DesktopApp')
                    document.getElementById('close'+$(this).attr("linkindex")).style.display='block';
            }, function () {
                $(this).removeClass("l-over");
                document.getElementById('close'+$(this).attr("linkindex")).style.display='none';
            }).click(function (e) {
                var linkindex = $(this).attr("linkindex");
                var link = links[linkindex];
                if(!bCloseApp)
                    f_open(link.url, link.title, link.icon,link.mtype,link.winw,link.winh);
                bCloseApp=false;
            });
            jlink.appendTo(winlinksul);
        }
	}
    var bCloseApp=false;
    function onCloseApp(i)
    {
        bCloseApp=true;
        var link = links[i];
        $.ligerDialog.confirm('确认删除？', function(yes) {
            if (yes) {
                $.post(
                    'Desktop.do',
                    {
                        Action: 'DelDesktopApp',
                        delid: link.id
                    },
                     function(data) {
                         if (data == "" || data == null) {
                             window.location.reload();
                             return true;
                         }
                         else {
                             $.ligerDialog.warn(data);
                             return false;
                         }
                     },
                    'text');
             }
           });
        return false;
    }

    $(window).resize(onResize);
    $.ligerui.win.removeTaskbar = function () { }; //不允许移除
    $.ligerui.win.createTaskbar(); //页面加载时创建任务栏

    linksInit();
    onResize();

    <%if (request.getSession().getAttribute("User") != null)
    {%>
    $(function ()
    {
        menu1 = $.ligerMenu({ top: 100, left: 100, width: 120, items:
        [
        { text: '背景', click: onMenuitemBg }
        ]
        });

        $("#winlinks").bind("contextmenu", function (e)
        {
            menu1.show({ top: e.pageY, left: e.pageX });
            return false;
        });

    });
    <%} %>
    function onMenuitemBg(item, i)
    {
        var win = $.ligerDialog.open(
            { url: 'SelectBg.jsp',height: 500,  width: 600,  isResize: true, modal: false, title: '选择背景', slide: false
                //        , buttons: [
                //            { text: '确定', onclick: function (item, Dialog, index) {
                //                win.hide();
                //            }
                //            }
                //        ]
            });
    }
    
    function onSelectBg(src, filename) {
        $.post(
            'Desktop.do',
            {
                Action: 'SetBackImg',
                BackImg: filename
            },
             function(data) {
                 if (data == "" || data == null) {
                     document.body.style.background='url('+src+') no-repeat  center center;';
                     return true;
                 }
                 else {
                     $.ligerDialog.warn(data);
                     return false;
                 }
             },
             'text');
    }
    
    
    //定时更新用户在线状态
    function UpdateOnlineState() {

        $.post(
            'Desktop.do',
            {
                Action: 'UpdateOnlineState'
            },
            function(data) {
                if (data == "" || data == null) {
                    return false;
                }
                else {
                    return true;
                }
            },
            'text'
		);
        window.setTimeout(UpdateOnlineState, 10000);
    }
    <%if (request.getSession().getAttribute("User") != null)
    {%>
    //每隔10秒更新一次
    window.setTimeout(UpdateOnlineState, 10000);
    <%} %>
    //登录
    <%if (request.getSession().getAttribute("User") == null)
    {%>
    var winLogin = $.ligerDialog.open(
            { url: '../Login.jsp',height: 250,  width: 450,  isResize: true, modal: true, title: '登录', slide: false
                //        , buttons: [
                //            { text: '确定', onclick: function (item, Dialog, index) {
                //                win.hide();
                //            }
                //            }
                //        ]
            });
    <%}
      else{ %>
    
    var winUser = $.ligerDialog.open(
            { url: '../Security/User/UserPanel.jsp',height: 500,  width: 800,  isResize: true, modal: true, title: '用户', slide: false
            });
    <%}%>
</script>
</html>
<!--修正ie6下png图不透明问题-->
<script src="../js/DD_belatedPNG_0.0.8a.js" type="text/javascript"></script>     
<script type="text/javascript">
    if ($.browser.msie && ($.browser.version == "6.0")) {
        DD_belatedPNG.fix('div, ul, img, li, input , a');
    }    
</script>